import { i18n } from '@/config/i18n.config';
import { Tsrv, ifs } from '@/services';
import { N_oInteraction } from '@/types';
import Vue from 'vue';

/**
 * 通过editrender获取itemrender
 * @param render
 */
const getSearchRender = (render: any) => {
  const itemRender = render;
  if (itemRender.name === 'oNumberInput') {
    itemRender.name = 'oNumberInputRange';
  } else if (itemRender.name === 'oDatePicker') {
    const type = itemRender.props.type;
    if (type === 'date') {
      itemRender.props.type = 'daterange';
    } else if (type === 'time') {
      itemRender.props.type = 'timerange';
    } else if (type === 'datetime') {
      itemRender.props.type = 'datetimerange';
    }
  } else if (itemRender.name === 'oM2oSelector') {
    let isM2o = true;
    if (itemRender.props.m2oConfig && itemRender.props.m2oConfig.fields) {
      const fields = itemRender.props.m2oConfig.fields;
      if (fields && fields.length > 0) {
        if (Tsrv.utils.find(fields, el => el.isReturn === true)) {
          isM2o = false;
        }
      } else {
        itemRender.props.m2oConfig.fields = [];
      }
    } else {
      itemRender.props.m2oConfig.fields = [];
    }
    if (isM2o) {
      const toField = itemRender.props.m2oConfig.toField;
      const find = Tsrv.utils.find(
        itemRender.props.m2oConfig.fields,
        el => el.title === toField
      );
      itemRender.props.m2oConfig.i18n = true;
      if (find) {
        find.isReturn = true;
      } else {
        itemRender.props.m2oConfig.fields.push({
          filter: '',
          isReturn: true,
          isShow: true,
          sort: '',
          title: toField
        });
      }
    }
  }
  return itemRender;
};

/**
 * 获取默认的toolbar配置
 * @param type
 */
// eslint-disable-next-line consistent-return
const getDefaultToolbar = (type: string): any => {
  const setting = {
    insert: true,
    delete: true,
    save: true,
    edit: true
  };

  const basic = {
    // insert: true,
    // delete: true,
    // save: true,
    // edit: true,
    refresh: true,
    default: true,
    print: true,
    addon: []
  };

  const data = {
    exportXML: false,
    import: true,
    export: true
  };

  const audit = {
    audit: false,
    unaudit: false
  };

  const billAudit = {
    requestAudit: false,
    antiAudit: false,
    auditStatus: false,
    accountPosted: false,
    cancelPost: false,
    caseclosed: false,
    anticlosing: false,
    freeze: false,
    unfreeze: false,
    void: false
  };

  const jump = {
    next: true,
    jumpLast: true,
    previous: true,
    jumpFirst: true
  };

  const tree = {
    expandAll: true,
    contractAll: true,
    selectMode: true
  };

  switch (type) {
    case 'baseform':
      return Tsrv.utils.merge(basic, setting, jump);
    case 'basegrid':
      // return Tsrv.utils.merge(basic, jump, data, audit, {
      return Tsrv.utils.merge(basic, setting, data, audit, billAudit, {
        setup: false,
        importErrorFilter: false,
        pasteColumn: false
      });
    case 'refbasegrid':
      return Tsrv.utils.merge(basic, setting, data, audit, {
        setup: false,
        importErrorFilter: false,
        pasteColumn: false
      });
    case 'baseview':
      return Tsrv.utils.merge(basic, data, audit, {
        // return Tsrv.utils.merge(basic, setting, data, audit, {
        setup: false,
        importErrorFilter: false,
        pasteColumn: false
      });
    case 'basepanel':
      return Tsrv.utils.merge(basic, setting, jump, data, audit, billAudit);
    case 'treegrid':
      return Tsrv.utils.merge(tree, {
        addon: []
      });

    default:
      break;
  }
};

/**
 * 获取toolbar的配置
 * @param config
 * @param type
 */
const getToolbarConfig = (config: any, type: string) => {
  let defaultToobar = getDefaultToolbar(type);
  if (config) {
    for (const key in defaultToobar) {
      if (key !== 'addon') {
        defaultToobar[key] = {
          isShow: config[key] === undefined ? defaultToobar[key] : config[key],
          isDisable: false,
          auth: false,
          value: null
        };
      } else {
        if (config.addon && config.addon.length > 0) {
          config['addon'].forEach(el => {
            el.auth = false;
            el.isDisable = false;
            el.isShow = true;
            if (el.children.length > 0) {
              el.children.forEach(child => {
                child.auth = false;
              });
            }
          });
        } else {
          config['addon'] = [];
        }
        defaultToobar['addon'] = config['addon'];
      }
    }
  } else {
    defaultToobar = null;
  }
  return defaultToobar;
};

/**
 * 执行自定义按钮事件
 * @param title 标题
 * @param action 动作
 * @param params 参数
 */
const doCustomBtnAction = (
  title: string,
  action: string,
  params: any,
  noConfirm: boolean = false
): Promise<[any, string] | boolean> => {
  return new Promise((resolve, reject) => {
    if (!Tsrv.utils.isEmpty(action)) {
      if (noConfirm) {
        const msg = Vue.prototype.$Message.loading({
          content: `${i18n.t(
            'others.beingexecuted'
          )} ${Vue.prototype.$srv.getI18nBySrv(title)}...`,
          duration: 0
        });
        const url = Tsrv.url.fun;
        const p = { spName: action, params };
        Tsrv.standardPostReq<ifs.I_setDataRes, any>(p, url)
          .then(r => {
            msg();
            // const [res, err] = r;
            // if (err !== undefined || !res.success) {
            //   resolve(true);
            // } else {
            //   Vue.prototype.$msg(res.data.msg);
            //   resolve(false);
            // }
            resolve(r);
          })
          .catch(e => {
            msg();
            // resolve(false);
            reject(e);
          });
      } else {
        Vue.prototype.$Modal.confirm({
          // title: "自定义功能",
          okText: i18n.t('others.ok'),
          cancelText: i18n.t('others.cancel'),
          title: i18n.t('others.customfunction'),
          // content: `是否执行${Vue.prototype.$srv.getI18nBySrv(title)}`,
          content: `${i18n.t(
            'others.whethertoexecute'
          )} ${Vue.prototype.$srv.getI18nBySrv(title)}`,
          onOk: () => {
            const msg = Vue.prototype.$Message.loading({
              // content: `正在执行${Vue.prototype.$srv.getI18nBySrv(title)}...`,
              content: `${i18n.t(
                'others.beingexecuted'
              )} ${Vue.prototype.$srv.getI18nBySrv(title)}...`,
              duration: 0
            });
            const url = Tsrv.url.fun;
            const p = { spName: action, params };
            Tsrv.standardPostReq<ifs.I_setDataRes, any>(p, url)
              .then(r => {
                msg();
                // const [res, err] = r;
                // if (err !== undefined || !res.success) {
                //   resolve(true);
                // } else {
                //   Vue.prototype.$msg(res.data.msg);
                //   resolve(false);
                // }
                resolve(r);
              })
              .catch(e => {
                msg();
                // resolve(false);
                reject(e);
              });
          },
          onCancel: () => {
            resolve(false);
          }
        });
      }
    } else {
      // reject("执行自定义按钮事件失败：动作为空");
      reject(i18n.t('others.failedactionempty'));
    }
  });
};

const doRequestAudit = (
  funInfo: { funID: string; funName: string },
  params: any
): Promise<any> => {
  return new Promise((resolve, reject) => {
    const saveDetFields = (): Array<N_oInteraction.I_field> => [
      {
        fieldID: '222301287968935937',
        field: 'title',
        type: 'varchar(45)',
        isShow: true,
        notNull: false,
        defValue: '',
        comment: '',
        selectionID: null,
        disabled: false,
        defaultFilter: false,
        nodeData: false,
        footerMethod: null,
        formatter: {
          type: '',
          decimal: 0,
          thousandmark: false,
          currency: ''
        },
        actions: [],
        auxProp: '',
        minWidth: '',
        appWeight: '',
        isDes: false,
        many2one: {
          toTable: '',
          toField: '',
          isDropdown: false,
          customSearch: '',
          multiConnect: '',
          isFunLayout: true,
          fields: []
        },
        align: 'left',
        subQuery: ''
      }
    ];
    const saveDetCompBind = (): any => {
      return {
        value: true, // 显示窗口
        width: '400',
        height: '200',
        type: 'confirm',
        mask: false,
        // 是否允许窗口边缘拖动调整窗口大小
        resize: true,
        // 标题是否标显示最大化与还原按钮
        showZoom: true,
        showClose: true,
        // status: '',
        title: Tsrv.getI18nByValue('请输入审批标题'),
        showFooter: true,
        minWidth: 400,
        minHeiht: 300,
        // 是否允许按 Esc 键关闭窗口
        escClosable: false, // default false
        // showHeader: false,
        showTitleOverflow: true
      };
    };
    const oInteractionConf = (workID: string, uiID: string, formData?: any) => {
      const compcf = new N_oInteraction.T_funPanel();
      compcf.group = {
        saveDet: [
          {
            form: {
              uiID,
              formColumnNum: 1,
              fields: saveDetFields()
            }
          }
        ]
      };
      // compcf.initValue = {
      //   formData: {
      //     [uiID]: formData
      //   }
      // };
      const interactionCf: N_oInteraction.I_conf = {
        cmd: N_oInteraction.V_cmd.FUN_PANEL,
        workID,
        compBind: saveDetCompBind(),
        compConf: compcf
      };
      return interactionCf;
    };
    const workID = Tsrv.utils.custUUID(16);
    const uiID = Tsrv.utils.custUUID(16);
    Tsrv.utils
      .createModal('oInteraction', oInteractionConf(workID, uiID))
      .then((data: any) => {
        const title = data.data[uiID][0].value;
        if (Tsrv.noValue(title)) {
          Vue.prototype.$Message.warning('请输入审批标题');
          return;
        }
        const submitInfo = {
          title,
          content: `${Tsrv.getI18nBySrv(funInfo.funName)} 请审批`
        };
        if (!Tsrv.utils.isJSONString(params)) {
          params = JSON.stringify(params);
        }
        Tsrv.requestAudit(funInfo.funID, submitInfo, params)
          .then(res => {
            resolve(res);
          })
          .catch(e => {
            reject(e);
          });
      });
  });
};

const selectBill = (
  item: any,
  tableName: string,
  funcName: string,
  row: any
) => {
  return new Promise((resolve, reject) => {
    if (
      !Tsrv.utils.isEmpty(item.many2one.toTable) &&
      !Tsrv.utils.isEmpty(item.action)
    ) {
      const config = {};
      if (item.many2one.fields) {
        config['tableConfig'] = Tsrv.utils.getM2OConfigOption(
          item.many2one.fields,
          Tsrv.utils.clone(row, true)
        );
      }
      Tsrv.utils
        .createModal('oMagicBox', {
          source: {
            funid: null,
            field: item.many2one.toTable,
            limit: 999
          },
          config
        })
        .then((data: any) => {
          if (data && data.length > 0) {
            const msg = Vue.prototype.$Message.loading({
              // content: `正在选单`,
              content: i18n.t('prompt.selbilling'),
              duration: 0
            });
            data = data.map(el => {
              return el.id;
            });
            const params = {
              currentTable: tableName,
              currentFunc: funcName,
              source: item.many2one.toTable,
              data
            };
            const url = Tsrv.url.get;
            const p = { getName: item.acton, params };
            Tsrv.standardPostReq<ifs.I_setDataRes, any>(p, url)
              .then(r => {
                msg();
                const [res, err] = r;
                if (err !== undefined || !res.success) {
                  resolve(false);
                  // Vue.prototype.$msg("选单失败");
                  Vue.prototype.$msg(i18n.t('warm.errBill'));
                } else {
                  resolve(res);
                  Vue.prototype.$msg('50005,FE,0,');
                }
              })
              .catch(() => {
                msg();
                // reject("选单失败");
                reject(i18n.t('warm.errBill'));
              });
            // lib.httpRequest
            //   .get(item.action, params)
            //   .then(res => {
            //     msg();
            //     res = res.data;
            //     if (res.success) {
            //       resolve(res);
            //       Vue.prototype.$msg('50005,FE,0,');
            //     } else {
            //       resolve(false);
            //       // Vue.prototype.$msg("选单失败");
            //       Vue.prototype.$msg(i18n.t('warm.errBill'));
            //     }
            //   })
            //   .catch(() => {
            //     msg();
            //     // reject("选单失败");
            //     reject(i18n.t('warm.errBill'));
            //   });
          }
        });
    } else {
      resolve(false);
    }
  });
};

export default {
  getSearchRender,
  getToolbarConfig,
  /**
   *@deprecated :将在2.0版本后续版本中弃用,请改用Tsrv.doEvent
   */
  doCustomBtnAction,
  doRequestAudit,
  // loadSelectOption,
  selectBill
};
